<template>
  <div class="goodsBox">
    <div style="background-color: white">
      <div class="listName">
        <el-button size="small" type="primary" plain @click="goBack">返回</el-button>
        <div>
          <el-button :disabled="disableIinput" size="small" type="success" plain @click="submitForm">保存</el-button>
        </div>
      </div>
      <el-form ref="dialogBindData" :model="dialogBindData" :rules="rules" label-width="20%" status-icon>
        <el-row :gutter="150">
          <el-col :xs="24" :sm="24" :md="16" :lg="13" :xl="13">
            <el-form-item label="活动名称" prop="activityName">
              <el-input :disabled="disableIinput" v-model="dialogBindData.activityName" size="small" type="text" placeholder="请输入活动名称"/>
            </el-form-item>
            <el-form-item label="活动时间">
              <el-date-picker
                v-if="dialogType !== 3"
                v-model="dialogBindData.startTime"
                :picker-options="startDatePicker"
                size="small"
                align="right"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择开始日期"/>
              <el-date-picker
                v-if="dialogType !== 3"
                v-model="dialogBindData.endTime"
                :picker-options="endDatePicker"
                size="small"
                align="right"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结束日期"/>
              <span v-if="dialogType === 3">{{ dialogBindData.startTime +' ~ '+dialogBindData.endTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="table-wrapper">
      <el-button v-if="dialogType !== 3" type="primary" size="mini" plain @click="chooseGoods">选择商品</el-button>
      <p v-else style="color: #666;">商品列表</p>

      <el-table v-loading="!dataShop" :data="dataShop" stripe border empty-text="暂无数据">

        <el-table-column align="center" prop="itemName" label="商品名称"/>

        <el-table-column align="center" label="商品图片">
          <template slot-scope="scope">
            <img :src="scope.row.prizePicUrl" width="50px" height="50px">
          </template>
        </el-table-column>

        <el-table-column align="center" prop="itemId" label="商品ID"/>

        <el-table-column align="center" label="抢购价格">
          <template slot-scope="scope">
            <el-input :disabled="disableIinput" v-model="scope.row.activityPrice" size="mini" type="number" />
          </template>
        </el-table-column>

        <el-table-column align="center" prop="marketPrice" label="原始价格"/>

        <el-table-column align="center" label="数量限制">
          <template slot-scope="scope">
            <el-input :disabled="disableIinput" v-model="scope.row.activityCount" size="mini" type="number" />
          </template>
        </el-table-column>

        <el-table-column v-if="dialogType === 3 " align="center" label="购买名单">
          <template slot-scope="scope">
            <span style="color: #0a76a4;cursor: pointer" @click="itemCheck(scope.row)">查看</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="230px">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" plain @click.native.prevent="del(scope.$index, dataShop)" >删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!--弹框-->
      <el-dialog
        :visible.sync="dialogState"
        :close-on-click-modal="false"
        :before-close="handleClose"
        title="选择商品"
        top="5vh"
        width="60%">
        <template>
          <div v-if="dialogType !== 3" style="padding: 0 30px;">
            <el-table v-loading="!dataOption" :data="dataOption" :cell-class-name="cellcb" stripe border empty-text="暂无数据" @selection-change="selectChange">

              <el-table-column align="center" type="selection" width="55"/>

              <el-table-column align="center" prop="itemTitle" label="商品名称"/>

              <el-table-column align="center" label="商品图片">
                <template slot-scope="scope">
                  <img :src="scope.row.defaultPicUrl" width="50px" height="50px">
                </template>
              </el-table-column>

              <el-table-column align="center" prop="itemId" label="商品ID"/>

            </el-table>
            <!--分页-->
            <el-pagination
              :current-page="pageNo"
              :page-sizes="[10, 20, 30]"
              :page-size="pageSize"
              :total="rowCount"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
          </div>
          <div v-else style="padding: 0 30px;">
            <p style="color: #666;">购买名单</p>
            <el-table v-loading="!purchasingList" :data="purchasingList" height="600" stripe border empty-text="暂无数据">

              <el-table-column type="index" align="center" width="50" label="序号"/>

              <el-table-column align="center" prop="nickName" label="用户名称"/>

              <el-table-column align="center" prop="mobilePhone" label="手机号码"/>

              <el-table-column align="center" prop="itemName" label="商品名称"/>

              <el-table-column align="center" label="商品图片">
                <template slot-scope="scope">
                  <img :src="scope.row.picUrl" width="50px" height="50px">
                </template>
              </el-table-column>

              <el-table-column align="center" prop="sellerItemNo" label="商品编码"/>

              <el-table-column align="center" prop="createTime" label="购买时间"/>

              <el-table-column align="center" prop="fullAddr" label="收货地址"/>

            </el-table>
          </div>
        </template>
        <div class="btns-wrapper">
          <el-button size="small" @click="handleClose">取 消</el-button>
          <el-button v-if="dialogType !== 3" size="small" type="primary" @click="submmitFun">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as activity from '../../api/activity'
import { getUserInformation } from '@/utils/auth'
export default {
  data() {
    return {
      pageNo: 1,
      pageSize: 10,
      rowCount: null, // 总条数
      // 弹框
      dialogState: false,
      dialogType: null, // 1 -新增  2 - 编辑  3 -查看
      // 编辑数据
      editData: null,
      // 表格数据
      dataOption: null,
      selectData: null,
      // 商品表格
      dataShop: [],
      // 购买名单
      purchasingList: null,
      // 提交内容
      dialogBindData: {
        activityName: '',
        startTime: '',
        endTime: ''
      },
      rules: {
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      disableIinput: false, // 禁用
      // 时间组件控制
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),

      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  beforeMount() {
    this.dialogType = this.$route.params.type
    this.editData = this.$route.params.data
    if (this.dialogType === undefined || this.dialogType === null) {
      this.$router.go(-1)
    } else {
      if (this.dialogType === 2) {
        this.reBindData(this.editData)
      } else if (this.dialogType === 3) {
        this.disableIinput = true
        this.reBindData(this.editData)
      }
    }
  },
  methods: {
    // 获取用户信息
    getUser() {
      return JSON.parse(getUserInformation())
    },
    getList(cb) {
      const param = {
        current: this.pageNo,
        size: this.pageSize,
        itemType: 0
      }
      activity.getshopListnew(param).then(res => {
        if (res.data.code !== 1) {
          this.$message.error(res.data.msg)
          return false
        }
        if (res.data.data === 'null' || res.data.data === null) {
          return false
        }
        // 初始话表格数据
        const dataArr = res.data.data.records
        for (const i in dataArr) {
          dataArr[i].checkde = false
          if (dataArr[i].listStatus !== 1) {
            dataArr.splice(i, 1)
          }
        }

        if (this.dataShop.length !== 0) {
          for (const val of dataArr) {
            for (const data of this.dataShop) {
              if (val.itemId === data.itemId) {
                val.checkde = true
              }
            }
          }
          this.dataOption = dataArr
        } else {
          this.dataOption = dataArr
        }
        // 初始化分页数据
        this.rowCount = dataArr.length
        this.pageSize = res.data.data.size
      })
    },
    // 保存
    submitForm() {
      if (this.dataShop === null || this.dataShop.length === 0) {
        this.$message({
          message: '请选择商品',
          type: 'warning'
        })
        return false
      }
      const param = {
        activityName: this.dialogBindData.activityName,
        startTime: this.dialogBindData.startTime,
        endTime: this.dialogBindData.endTime,
        activityType: 0,
        list: this.dataShop
      }
      if (this.getUser().sellerId !== null) {
        param.sellerId = this.getUser().sellerId
      }
      if (this.dialogType === 2) {
        param.id = this.editData.id
      }
      this.$refs.dialogBindData.validate((valid) => {
        if (valid) {
          if (this.dialogType === 1) {
            const loading = this.$loading({
              lock: true,
              text: '保存中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            activity.addSnapupList(param).then(res => {
              loading.close()
              if (res.data.code !== 1) {
                this.$message({
                  message: res.data.msg,
                  type: 'warning'
                })
                this.buttonState = false
                return false
              }
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.$router.go(-1)
            }).catch(res => {
              this.$message({
                type: 'info',
                message: res.message
              })
              loading.close()
            })
          } else {
            const loading = this.$loading({
              lock: true,
              text: '保存中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            activity.addSnapupList(param).then(res => {
              loading.close()
              if (res.data.code !== 1) {
                this.$message({
                  message: res.data.msg,
                  type: 'warning'
                })
                this.buttonState = false
                return false
              }
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              this.$router.go(-1)
            }).catch(res => {
              this.$message({
                type: 'info',
                message: res.message
              })
              loading.close()
            })
          }
        } else {
          return false
        }
      })
    },
    // 删除
    del(index, rows) {
      rows.splice(index, 1)
    },
    // 选择商品
    chooseGoods() {
      this.dialogState = true
      this.getList()
    },
    selectChange(data) {
      this.selectData = data
    },
    // 确认商品
    submmitFun() {
      if (this.selectData === undefined || this.selectData === null) {
        this.$message({
          type: 'warning',
          message: '请选择商品'
        })
        return false
      }
      for (const val of this.selectData) {
        const obj = {}
        obj.activityCount = ''
        obj.activityPrice = ''
        obj.itemId = val.itemId
        obj.itemName = val.itemTitle
        obj.itemType = val.itemType
        obj.okRate = val.okRate
        obj.prizePicUrl = val.defaultPicUrl
        obj.remark = val.remark
        obj.sellerId = val.sellerId
        obj.marketPrice = val.marketPrice
        this.dataShop.push(obj)
      }

      this.dataOption = null
      this.dialogState = false
    },
    // 查看抢购列表
    itemCheck(data) {
      this.dialogState = true
      const param = {
        startTime: this.editData.startTime,
        itemId: data.itemId
      }
      activity.activityOrder(param).then(res => {
        if (res.data.code !== 1) {
          this.$message.error(res.data.msg)
          return false
        }
        if (res.data.data === 'null' || res.data.data === null) {
          return false
        }
        this.purchasingList = res.data.data
      })
    },
    // 反显
    reBindData(data) {
      const shopArr = []
      for (const key in this.dialogBindData) {
        this.dialogBindData[key] = data[key]
      }
      for (const val of data.list) {
        const obj = {}
        obj.activityCount = val.activityCount
        obj.activityPrice = val.activityPrice
        obj.itemId = val.itemId
        obj.itemName = val.itemName
        obj.itemType = val.itemType
        obj.okRate = val.okRate
        obj.prizePicUrl = val.prizePicUrl
        obj.remark = val.remark
        obj.sellerId = val.sellerId
        obj.marketPrice = val.marketPrice
        obj.checkde = true
        shopArr.push(obj)
      }
      this.dataShop = shopArr
    },
    beginDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.dialogBindData.endTime) { // 如果结束时间不为空，则小于结束时间
            return new Date(self.dialogBindData.endTime).getTime() < time.getTime()
          } else {
            // return time. () > Date.now() //开始时间不选时，结束时间最大值小于等于当天
            console.log('开始时间不选时，结束时间最大值小于等于当天')
          }
        }
      }
    },
    processDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.dialogBindData.startTime) { // 如果开始时间不为空，则结束时间大于开始时间
            return new Date(self.dialogBindData.startTime).getTime() > time.getTime()
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
            console.log('开始时间不选时，结束时间最大值小于等于当天')
          }
        }
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageNo = val
      this.getList()
    },
    handleClose() {
      this.dialogState = false
      this.dataOption = null
      this.purchasingList = null
    },
    cellcb(row) {
      if (row.row.checkde === true) {
        return 'myCell'
      }
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>
<style type="text/scss" lang="scss">
  .myCell .el-checkbox__input {
    display: none
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .listName{
    margin: 0;
    padding: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .btns-wrapper{
    display: flex;
    justify-content: flex-end;
    padding: 20px;
  }
  .table-wrapper{
    padding: 30px;
    background-color: #fff;
  }
</style>
